package handler

import (
	"encoding/json"
	"novel-mng-sys/cache"
	"novel-mng-sys/model"
	"novel-mng-sys/pkg"
	"time"

	"github.com/gin-gonic/gin"
)

func Login(c *gin.Context) {

	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "字段为空",
		})
		return
	}

	redis_login_key := "login_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_login_key).Int()

	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "错误三次",
		})
		return
	}

	var user model.User
	err := model.DB.Where("username = ?", username).First(&user)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "查询失败",
		})
		return
	}

	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "用户不存在",
		})
		return
	}

	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_login_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_login_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 400,
				"msg":  "错误三次，封禁两小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "账户或密码错误",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登陆成功",
	})
	return

}

func List(c *gin.Context) {

	var ser []model.Service

	redis_list_key := "list_"
	result, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()

	if result == "" {
		model.DB.Find(&ser)
		jsonData, _ := json.Marshal(ser)
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &ser)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "列表成功",
		"data": ser,
	})
	return

}

func Detail(c *gin.Context) {

	id := c.Query("id")

	var ser model.Service

	redis_detail_key := "detail_" + id
	result, _ := cache.Rdb.Get(cache.Ctx, redis_detail_key).Result()

	if result == "" {
		model.DB.Where("id = ?", id).First(&ser)
		jsonData, _ := json.Marshal(ser)
		cache.Rdb.Set(cache.Ctx, redis_detail_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &ser)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取详情成功",
		"data": ser,
	})
	return

}

func Commit(c *gin.Context) {

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
	})
	return

}
